<?php
namespace addons\TfFutures\handler;

use linslin\yii2\curl;
class GatherSina extends Gather
{
    public $list = [];
    public function run(){
        $stime = time();
        list( $status,$cate ) = $this->loadMounth();
        if( $status ){
            $list       = $this->loadTreaty($cate[0],$cate[1]);
            $this->list = $this->loadData($cate[0],$list);
            $this->stockId = $cate[0];
            $this->month   = $cate[1];
        }
        $this->insert($this->list);
    }

    //获取合约
    public function loadMounth(){
        $curl = new curl\Curl();$stockId = null;$list = [];
        $resp = $curl->get('http://stock.finance.sina.com.cn/futures/api/openapi.php/StockOptionService.getStockName');
        if ($curl->errorCode == null) {
            $response = json_decode($resp,true);
            if( !empty($response['result']['data']['contractMonth']) ){
                $stockId = $response['result']['data']['stockId'];
                $month   = array_unique($response['result']['data']['contractMonth']);

                foreach ($month as $m){
                    $resp = $curl-> get('http://stock.finance.sina.com.cn/futures/api/openapi.php/StockOptionService.getRemainderDay?date='.str_replace("-","",$m).'01');
                    if( $curl->errorCode == null ){
                        $response = json_decode($resp,true);
                        if( !in_array($response['result']['data']['expireDay'],$list) ){
                            $list[] = $response['result']['data']['expireDay'];
                        }
                    }
                }


                return [true,[$stockId,$list]];
            }

        }
        return [false,$list];
    }

    public function loadTreaty($stockId,$mounth){
        $tmpList = [];
        foreach ($mounth as $m)
        {
            $curl = new curl\Curl();
            $resp = $curl-> get('http://hq.sinajs.cn/list=OP_UP_'.$stockId.str_replace("-","",substr($m,2,5)));
            if ($curl->errorCode == null) {
                $response = explode('="',$resp);
                if( !empty($response[1]) ){

                    $response = array_unique(explode(',',substr($response[1],0,-4)));
                    $tmpList[$m]['rise'] = $response;
                }
            }

            $resp = $curl-> get('http://hq.sinajs.cn/list=OP_DOWN_'.$stockId.str_replace("-","",substr($m,2,5)));
            if( $curl->errorCode == null )
            {
                $response = explode('="',$resp);
                if( !empty($response[1]) ){

                    $response = array_unique(explode(',',substr($response[1],0,-4)));
                    $tmpList[$m]['fall'] = $response;
                }
            }

        }
        return $tmpList;
    }

    public function loadData( $stockId,$list ){
        $tmplist = [];$curl = new curl\Curl();
        foreach ( $list as $month=>$rise_falls ){
            $product = [];
            foreach ($rise_falls as $rise_fall=>$treaty){
                $resp = $curl-> get('http://hq.sinajs.cn/list='.implode(',',$treaty));
                if( $curl->errorCode == null )
                {
                    $response = explode(';',$resp);
                    foreach($response as $productStr){
                        $productStr = explode('"',$productStr);
                        if( !empty($productStr[1]) ){

                            $code        = substr($productStr[0],strpos($productStr[0],'hq_str_')+7,-1);
                            $products    = explode(',',$productStr[1]);
                            $product[]   = [
                                'code'          => $code,
                                'name'          => mb_convert_encoding($products['37'],'UTF-8','gbk'),
                                'name_code'     => substr($code,strrpos($code,'_')+1),
                                'contract_size' => 1,
                                'trade_time'    => null,
                                'zoom_size'     => 1,
                                'rise_fall'     => $rise_fall,
                                'unit'          => 1,
                                'unit_price'    => 1,
                                'unit_step'     => 1,
                                'overfee'       => 0,
                                'overtime'      => '04:00:00',
                                'deposit'       => 100,
                                'servicefee'    => 70,
                                'maxrise'       => 100,
                                'minrise'       => 0,
                                'maxlost'       => 100,
                                'minlost'       => 0,
                                'risk'          => 0,
                                'on_sale'       => 'on',
                                'product_price' => [
                                    'code'           => $code,
                                    'wave'           => $products[6],
                                    'toa_price'      => $products[7],
                                    'price'          => $products[2],
                                    'buy_price'      => $products[1],
                                    'buy_price2'     => $products[24],
                                    'buy_price3'     => $products[26],
                                    'buy_price4'     => $products[28],
                                    'buy_price5'     => $products[30],
                                    'sell_price'     => $products[3],
                                    'sell_price2'    => $products[18],
                                    'sell_price3'    => $products[16],
                                    'sell_price4'    => $products[14],
                                    'sell_price5'    => $products[12],
                                    'volume'         => $products[0]+$products[4],
                                    'position'       => $products[5],
                                    'open'           => $products[9],
                                    'close'          => $products[8],
                                    'high'           => $products[10],
                                    'low'            => $products[11],
                                    'time'           => $products[32],
                                ]
                            ];
                        }
                    }
                }
            }
            if( !empty($product) ){
                $tmplist[$month] = [
                    'name'    => $stockId.'-'.$month,
                    'sdate'   => $month,
                    'on_sale' => 'on',
                    'product' => $product
                ];
            }
        }
        return $tmplist;
    }
}